def is_numeric(num):
    if num.isdigit():
        return True
    # 判断是否是浮点数，只能判断常规浮点数。
    s = num.split('.')
    if len(s) > 2:
        return False
    else:
        for si in s:
            if not si.isdigit():
                return False
        return True

def calculate_expression(nums, ops):
    c = 0
    while c < len(ops):
        if ops[c] == '*':
            nums[c] = nums[c] * nums[c + 1]
            del nums[c + 1]
            del ops[c]
        elif ops[c] == '/':
            nums[c] = nums[c] / nums[c + 1]
            del nums[c + 1]
            del ops[c]
        else:
            c += 1

    j = 0
    while j < len(ops):
        if ops[j] == '+':
            nums[j] = nums[j] + nums[j + 1]
            del nums[j + 1]
            del ops[j]
        elif ops[j] == '-':
            nums[j] = nums[j] - nums[j + 1]
            del nums[j + 1]
            del ops[j]

    return nums[0]

print("计算器plus正在启动")

while True:
    user_input = input("请输入表达式，如1+(1+1)，2/3/4，(输入 'q' 退出)：")

    if user_input.lower() == 'q':
        print("退出程序。")
        break
    elif user_input.strip() == '':
        continue
    else:
        nums = []
        ops = []
        stack = []
        current_num = ""
        # 移除所有空格，归一化输入
        user_input = user_input.replace(' ','')

        for i in user_input:
            if i == '(':
                stack.append((nums, ops))
                nums = []
                ops = []
            elif i == ')':

                if current_num:
                    nums.append(float(current_num))
                    current_num = ""

                result = calculate_expression(nums, ops)

                nums, ops = stack.pop()
                nums.append(result)
            elif i in "+-*/":
                if current_num:
                    if is_numeric(current_num):
                        nums.append(float(current_num))
                        current_num = ""
                    else:
                        print("输入包含无效数字")
                        break
                ops.append(i)
            else:
                current_num += i


        if current_num:
            if is_numeric(current_num):
                nums.append(float(current_num))
            else:
                print("输入包含无效数字")
                continue

        if len(nums) - 1 != len(ops):
            print("请输入正确的表达式")
            continue

        result = calculate_expression(nums, ops)
        print(result)